package com.globagames.isometric.core.view
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.containers.Canvas;
	import mx.core.ScrollPolicy;
	
	public class DraggableBox extends Canvas
	{
		private var regX:Number;
		private var regY:Number;
		
		public function DraggableBox()
		{
			clipContent = true;
			horizontalScrollPolicy = ScrollPolicy.OFF;
			verticalScrollPolicy = ScrollPolicy.OFF;
		}
		protected function startDragging(event:MouseEvent):void
	    {
	        regX = event.stageX - x;
	        regY = event.stageY - y;
	        
	        systemManager.addEventListener(
	            MouseEvent.MOUSE_MOVE, systemManager_mouseMoveHandler, true);
	
	        systemManager.addEventListener(
	            MouseEvent.MOUSE_UP, systemManager_mouseUpHandler, true);
	
	        systemManager.stage.addEventListener(
	            Event.MOUSE_LEAVE, stage_mouseLeaveHandler);
	    }
	    private function systemManager_mouseMoveHandler(event:MouseEvent):void
	    {
	        // during a drag, only the Panel should get mouse move events
	        // (e.g., prevent objects 'beneath' it from getting them -- see bug 187569)
	        // we don't check the target since this is on the systemManager and the target
	        // changes a lot -- but this listener only exists during a drag.
	        event.stopImmediatePropagation();
	        
	        move(event.stageX - regX, event.stageY - regY);
	    }
	    private function systemManager_mouseUpHandler(event:MouseEvent):void
	    {
	        if (!isNaN(regX))
	            stopDragging();
	    }
	    protected function stopDragging():void
	    {
	        systemManager.removeEventListener(
	            MouseEvent.MOUSE_MOVE, systemManager_mouseMoveHandler, true);
	
	        systemManager.removeEventListener(
	            MouseEvent.MOUSE_UP, systemManager_mouseUpHandler, true);
	
	        systemManager.stage.removeEventListener(
	            Event.MOUSE_LEAVE, stage_mouseLeaveHandler);
	
	        regX = NaN;
	        regY = NaN;
	    }
	    private function stage_mouseLeaveHandler(event:Event):void
	    {
	        if (!isNaN(regX))
	            stopDragging();
	    }

	}
}